<template>
  <div>
    <MyEcharts :option="option" />
  </div>
</template>
<script>
import { openApiStatisticalDataQueryResourceTypeTotal } from "@/api/admin/data/data";
import { LIBRARY } from "@/utils/config";
import Bus from "@/utils/bus.js";
const resourceArr = [
  { name: "课程", type: "course" },
  { name: "知识点", type: "knowledge" },
  { name: "图片", type: "photo" },
  { name: "文本", type: "text" },
  { name: "视频", type: "video" },
];

export default {
  components: {
    MyEcharts: () => import("@/components/myEcharts/index.vue"),
  },
  data() {
    return {
      listQuery: {
        // deptType: 1, //单位类型；1-校区，2-系，3-教研室
        // selection: 0, //是否精选课程，1-是，0-否
        sourceUnit: "", //单位
      },
      option: null,
    };
  },
  mounted() {
    this.getList();
    Bus.$on("sendSchoolId", (v) => {
      let { sourceUnit } = v;
      Object.assign(this.listQuery, { sourceUnit });
      this.getList();
    });
  },
  beforeDestroy() {
    Bus.$off("sendSchoolId");
  },
  methods: {
    getList() {
      openApiStatisticalDataQueryResourceTypeTotal(this.listQuery).then(
        (res) => {
          let { data } = res.data;
          this.initEcharts(data);
        }
      );
    },
    initEcharts(data) {
      let newData = JSON.parse(JSON.stringify(data[0]));
      let series = [];
      Object.keys(newData).forEach((key) => {
        newData[key] = this.pushData(newData[key]);
        let op = {
          type: "bar",
          name: this.titleFilter(key),
          showBackground: true,
          data: newData[key].map((v) => v.sumNum),
        };
        series.push(op);
      });
      // 柱状图
      this.option = {
        tooltip: {},
        xAxis: {
          type: "category",
          data: LIBRARY.filter((v) => v.type <= 6).map((m) => m.name),
        },
        yAxis: {},
        series: series,
      };
      var legend = {
        data: resourceArr.map((v) => v.name),
      };
      this.$set(this.option, "legend", legend);
    },
    titleFilter(data) {
      return resourceArr.filter((v) => v.type == data)[0].name;
    },
    //数据填充
    pushData(data) {
      if (data.length != 6) {
        let cur = data.map((v) => v.courseType);
        for (var i = 1; i <= 6; i++) {
          let courseType = i.toString();
          if (cur.indexOf(courseType) == -1) {
            data.push({ courseType, sumNum: "0" });
          }
        }
      }
      data.sort(this.createComparisonFunction("courseType"));
      return data;
    },
    //排序
    createComparisonFunction(propertyName) {
      return function (object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if (value1 < value2) {
          return -1;
        } else if (value1 > value2) {
          return 1;
        } else {
          return 0;
        }
      };
    },
  },
};
</script>